package org.xian.token.secutiry;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.xian.token.entity.SysUser;
import org.xian.token.mapper.SysUserMapper;

import javax.annotation.Resource;
import java.util.Collection;

/**
 * @author xian
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 这里从数据库查询用户信息，返回UserDetails是不够的。后面还需要校验用户信息是否正确，此外，还要返回token信息。
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserMapper.selectByUsername(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException(username);
        }
        // Spring Security 角色名称默认使用 "ROLE_" 开头
        // authorities.add 可以增加多个用户角色，对于一个用户有多种角色的系统来说，
        // 可以通过增加用户角色表、用户--角色映射表，存储多个用户角色信息

        // TODO 校验密码是否正确，如果密码不正确则直接抛出异常即可。

        if (false) {
            throw new BadCredentialsException("用户名或者密码错误");
        }

        // 给 Spring Security 传入用户名、用户密码、用户角色。
        Collection<? extends GrantedAuthority> authorities = sysUser.getAuthorities();
        return new User(sysUser.getUsername(), sysUser.getPassword(), authorities);
    }
}